
#合理模拟生产者消费者状态
import threading
import time
import random
#初始化金额，和控制的次数
gMoney=1000
gTimes=0
totalTime=10
gLock=threading.Lock()
class Producer():
    def run(self):
        while True:
            global gMoney
            global gTimes,totalTime
            gLock.acquire()
            # 在进行生产之前，先判断是否10次
            if gTimes >= 10:
                gLock.release()
                break
            money=random.randint(100,1000)
            gMoney+= money
            print("%s生产了%d元，还剩下%d元"%(threading.current_thread(),money,gMoney))
            totalTime+=1
            gLock.release()

class Consumer():
    def run(self):
        while True:
            global gMoney
            gLock.acquire()
            money=random.randint(100,1000)
            if money<=gMoney:
                gMoney-=money
                print("%s消费了%d元，还剩下%d元" % (threading.current_thread(), money, gMoney))
            else:
                if gTimes >= totalTime:
                    gLock.release()
                    break
                print("%s消费了%d元，剩余%d元，不足。" % (threading.current_thread(), money, gMoney))
            gLock.release()
def main():
    for x in range(5):
        t=Producer(name="生产者线程%d"%x)
        t.start()

    for x in range(3):
         t = Consumer("消费者线程%d"%x)
         t.start()
if __name__ == '__main__':
    main()